package top.tupobi.zing.service.socket;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;

public class ClientSocketReceiverThread implements Runnable {

    private DataInputStream mDataInputStream;
    private OnReceiveDataListener mOnReceiveDataListener;
    private volatile boolean mShouldReceiveData = true;
    private Socket mSocket;

    void setOnReceiveDataListener(OnReceiveDataListener onReceiveDataListener) {
        mOnReceiveDataListener = onReceiveDataListener;
    }

    ClientSocketReceiverThread(DataInputStream dataInputStream, Socket socket) {
        mDataInputStream = dataInputStream;
        this.mSocket = socket;
    }

    void stopReceiveData() {
        this.mShouldReceiveData = false;
        this.mDataInputStream = null;
    }

    @Override
    public void run() {
        try {
            while (mShouldReceiveData && mDataInputStream != null && !mSocket.isClosed()) {
                String str = mDataInputStream.readUTF();
                mOnReceiveDataListener.onReceiveData(str);
            }
        } catch (SocketException e) {
            e.printStackTrace();
            mOnReceiveDataListener.onDisConnectedSocketException();
        } catch (EOFException e) {
            e.printStackTrace();
            mOnReceiveDataListener.onDisconnectedEOFException();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("接收消息异常：IOException");
            mOnReceiveDataListener.onDisconnectedIOException();
        }
    }
}

interface OnReceiveDataListener {
    void onReceiveData(String data);

    void onDisconnectedEOFException();

    void onDisConnectedSocketException();

    void onDisconnectedIOException();
}
